<script>
import { isActive } from "@theme/helpers/utils";

export default {
  computed: {
    headers() {
      const headers = (this.$page.headers || []).filter(
        (header) => header.level === 2
      );
      return headers;
    },
  },
  data() {
    return {};
  },
  methods: {
    isLinkActive(header) {
      const active = isActive(this.$route, this.$page.path + "#" + header.slug);
      if (active) {
        setTimeout(() => {
          // console.log(document.querySelector(`.${header.slug}`));
          document.querySelector(`.${header.slug}`).scrollIntoView();
        }, 300);
      }
      return active;
    },
  },
  render(h) {
    return h(
      "ul",
      {
        class: { "sub-sidebar-wrapper": true },
        style: { width: (this.$page.headers || []).length > 0 ? "12rem" : "0" },
      },
      [
        ...(this.$page.headers || []).map((header) => {
          return h(
            "li",
            {
              class: {
                active: this.isLinkActive(header),
                [`level-${header.level}`]: true,
              },
              attr: { key: header.title },
            },
            [
              h(
                "router-link",
                {
                  class: { "sidebar-link": true, [`${header.slug}`]: true },
                  props: { to: `${this.$page.path}#${header.slug}` },
                },
                header.title
              ),
            ]
          );
        }),
      ]
    );
  },
};
</script>

<style lang="stylus" scoped>
.sub-sidebar-wrapper {
  width: 15rem;
  padding-left: 0;
  list-style: none;
  font-size: 12px;

  li {
    padding: 0.2rem 0;
    cursor: pointer;
    border-left: 1px solid var(--border-color);

    a {
      padding: 0.35rem 1rem 0.35rem 0rem;
      color: var(--text-color);
    }

    &:hover {
      a {
        color: $accentColor;
      }
    }

    // 当前所在的段落
    &.active {
      border-left: 1px solid $accentColor;
      position: relative;
      padding-left: 20px !important;

      a {
        color: $accentColor;
      }

      a:before {
        content: '';
        position: absolute;
        width: 30px;
        height: 30px;
        background-image: url('../images/ribbon.svg');
        top: 5px;
        left: 0px;
        transform: rotate(260deg);
      }
    }

    &.level-1 {
      padding-left: 0.2rem;
    }

    &.level-2 {
      padding-left: 0.4rem;
    }

    &.level-3 {
      padding-left: 0.6rem;
    }

    &.level-4 {
      padding-left: 0.8rem;
    }

    &.level-5 {
      padding-left: 1rem;
    }

    &.level-6 {
      padding-left: 1.2rem;
    }
  }
}
</style>

